package com.suke.czx.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Redis工具类
 *
 * @author czx
 * @email object_czx@163.com
 * @date 2017-07-17 21:12
 */
@Component
public class RedisUtils {
	private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private JedisPool jedisPool;
	
	/**
     * 同步获取Jedis实例
     *
     * @return Jedis
     */
    public  Jedis getJedis() {
        return jedisPool.getResource();
    }
    /**
     * 释放jedis资源
     *
     * @param jedis
     */
    @SuppressWarnings("deprecation")
    public  void returnResource(final Jedis jedis) {
        if (jedis != null && jedisPool != null) {
            jedisPool.returnResource(jedis);
        }
    }
    @SuppressWarnings("deprecation")
    public  void returnBrokenResource(final Jedis jedis) {
        if (jedis != null && jedisPool != null) {
            jedisPool.returnBrokenResource(jedis);
        }
    }
    
    /**
     * 设置对象
     * 
     * @param key
     * @param obj
     * @return
     * @author jqlin
     */
    public  <T> String setObject(String key ,T obj,int expire){  
        Jedis jedis = getJedis();
         
        String result = null;
        try { 
            byte[] data=serialize(obj); 
            result = jedis.set(key.getBytes(), data);
            jedis.expire(key, expire);
        } catch (Exception e) {
        	logger.error("设置对象失败：" + e.getMessage(), e);
            returnBrokenResource(jedis);
        } finally {
            returnResource(jedis);
        }

        return result;
    }
    
    /**
     * 获取对象
     * 
     * @param key
     * @return
     * @author jqlin
     */
    @SuppressWarnings("unchecked")
    public  <T> T getObject(String key){  
        Jedis jedis = getJedis();
        if(jedis == null){
            return null;
        }
         
        T result = null;
        try { 
            byte[] data = jedis.get(key.getBytes());
            if(data != null && data.length > 0){
                result=(T)unserizlize(data);
            }
        } catch (Exception e) {
        	logger.error("获取对象失败：" + e.getMessage(), e);
            returnBrokenResource(jedis);
        } finally {
            returnResource(jedis);
        }

        return result;
    }
    /**
     * 删除key
     * 
     * @param keys
     * @return -5：Jedis实例获取失败，1：成功，0：失败
     * @author jqlin
     */
    public  long del(String... keys) {
        Jedis jedis = getJedis();
        if(jedis == null){
            return -5L;
        }
         
        long result = -5L;
        try {  
            result = jedis.del(keys);
        } catch (Exception e) {
        	logger.error(String.format("删除key=%s失败：" + e.getMessage(), keys), e);
            returnBrokenResource(jedis);
        } finally {
            returnResource(jedis);
        }

        return result;
    }
    
  //序列化 
    public static byte [] serialize(Object obj){
        ObjectOutputStream obi=null;
        ByteArrayOutputStream bai=null;
        try {
            bai=new ByteArrayOutputStream();
            obi=new ObjectOutputStream(bai);
            obi.writeObject(obj);
            byte[] byt=bai.toByteArray();
            return byt;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    //反序列化
    public static Object unserizlize(byte[] byt){
        ObjectInputStream oii=null;
        ByteArrayInputStream bis=null;
        bis=new ByteArrayInputStream(byt);
        try {
            oii=new ObjectInputStream(bis);
            Object obj=oii.readObject();
            return obj;
        } catch (Exception e) {
            
            e.printStackTrace();
        }
    
        
        return null;
    }
}
